package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.xiaoymin.knife4j.core.util.CollectionUtils;
import com.sky.constant.MessageConstant;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.ThreadLocalUtil;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
    private final OrderMapper orderMapper;
    private final OrderDetailMapper orderDetailMapper;
    private final ShoppingCartMapper shoppingCartMapper;
    private final UserMapper userMapper;
    private final AddressBookMapper addressBookMapper;

    private final WebSocketServer webSocketServer;

    @Autowired
    public OrderServiceImpl(OrderMapper orderMapper, OrderDetailMapper orderDetailMapper,
                            ShoppingCartMapper shoppingCartMapper,
                            UserMapper userMapper, AddressBookMapper addressBookMapper,
                            WebSocketServer webSocketServer) {
        this.orderMapper = orderMapper;
        this.orderDetailMapper = orderDetailMapper;
        this.shoppingCartMapper = shoppingCartMapper;
        this.userMapper = userMapper;
        this.addressBookMapper = addressBookMapper;
        this.webSocketServer = webSocketServer;
    }


    /**
     * 用户下单
     *
     * @param submitDTO dto
     * @return vo
     */
    @Override
    @Transactional
    public OrderSubmitVO submitOrder(OrdersSubmitDTO submitDTO) {
        //1.处理各种业务异常（收货地址为空，购物车数据为空）
        AddressBook addressBook = addressBookMapper.getById(submitDTO.getAddressBookId());
        if (addressBook == null) {
            //抛出业务异常
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        //查询当前用户购物车是否为空
        Long userId = ThreadLocalUtil.get();
        List<ShoppingCart> shoppingCarts = shoppingCartMapper.list(ShoppingCart.builder().userId(userId).build());
        if (shoppingCarts == null || shoppingCarts.isEmpty()) {
            //抛出业务异常
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        //2.向订单表插入一条数据
        Orders orders = new Orders();
        BeanUtils.copyProperties(submitDTO, orders);
        orders.setOrderTime(LocalDateTime.now()); //用户下单时间
        orders.setPayStatus(Orders.UN_PAID); //订单支付状态
        orders.setStatus(Orders.PENDING_PAYMENT); //订单状态;
        orders.setNumber(String.valueOf(System.currentTimeMillis())); //订单号
        orders.setPhone(addressBook.getPhone());//手机号
        orders.setConsignee(addressBook.getConsignee()); //收货人
        orders.setUserId(userId);//用户ID
        orders.setAddress(addressBook.getProvinceName() + addressBook.getCityName() + addressBook.getDistrictName() + addressBook.getDetail());//地址
        orderMapper.insert(orders);
        //3.向订单明细表插入n条数据
        List<OrderDetail> details = new ArrayList<>();
        shoppingCarts.forEach(shoppingCart -> {
            OrderDetail orderDetail = new OrderDetail(); //订单详细
            BeanUtils.copyProperties(shoppingCart, orderDetail);
            orderDetail.setOrderId(orders.getId()); //设置当前订单明细关联的订单ID
            details.add(orderDetail);
        });
        orderDetailMapper.insertBatch(details); //批量插入n条数据
        //4.用户下单成功清空购物车的商品
        shoppingCartMapper.deleteAllByUserId(userId);
        //5.封装vo返回结果
        return OrderSubmitVO.builder().id(orders.getId()).orderTime(orders.getOrderTime()).orderAmount(orders.getAmount()).orderNumber(orders.getNumber()).build();
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO dto
     * @return vo
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = ThreadLocalUtil.get();
        User user = userMapper.getById(userId);

//        //调用微信支付接口，生成预支付交易单
//        JSONObject jsonObject = weChatPayUtil.pay(ordersPaymentDTO.getOrderNumber(), //商户订单号
//                new BigDecimal(0.01), //支付金额，单位 元
//                "苍穹外卖订单", //商品描述
//                user.getOpenid() //微信用户的openid
//        );
        JSONObject jsonObject = new JSONObject();
        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        paySuccess(ordersPaymentDTO.getOrderNumber());
        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo 订单号
     */
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo, ThreadLocalUtil.get());

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder().id(ordersDB.getId()).status(Orders.TO_BE_CONFIRMED).payStatus(Orders.PAID).checkoutTime(LocalDateTime.now()).build();

        orderMapper.update(orders);

        //通过websocket 向客户端浏览器推送信息 type orderID CONTENT
        Map<String, Object> map = new HashMap<>();
        map.put("type", 1);
        map.put("orderId", ordersDB.getId());
        map.put("content", "订单号" + outTradeNo);
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }

    /**
     * 历史订单查询
     *
     * @param id 订单ID
     * @return 订单详情
     */
    @Override
    public OrderVO detail(Long id) {
        Orders orders = orderMapper.findById(id);
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders, orderVO);
        orderVO.setOrderDetailList(orderDetailMapper.findByOrderId(orders.getId()));
        return orderVO;
    }

    /**
     * 分页查询
     *
     * @param page     页码
     * @param pageSize 每页条数
     * @param status   订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消
     * @return 数据
     */
    @Override
    public PageResult<OrderVO> pageQuery4User(int page, int pageSize, Integer status) {
        PageHelper.startPage(page, pageSize);

        OrdersPageQueryDTO queryDTO = new OrdersPageQueryDTO();
        queryDTO.setStatus(status);
        queryDTO.setUserId(ThreadLocalUtil.get());

        Page<Orders> ordersPage = orderMapper.pageQuery(queryDTO);

        List<OrderVO> list = new ArrayList<>();
        if (ordersPage != null && !ordersPage.isEmpty()) {
            ordersPage.forEach(orders -> {
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders, orderVO);
                orderVO.setOrderDetailList(orderDetailMapper.findByOrderId(orders.getId()));
                list.add(orderVO);
            });
            return new PageResult<>(ordersPage.getTotal(), list);
        }
        return null;
    }

    /**
     * 取消订单
     *
     * @param id 订单ID
     */
    @Override
    public void userCancelById(Long id) {
        //先获取订单信息
        Orders ordersDB = orderMapper.findById(id);
        //如果为空则抛出异常
        if (ordersDB == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        //订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消
        if (ordersDB.getStatus() > 2) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Orders orders = new Orders();
        orders.setId(ordersDB.getId());

        if (ordersDB.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
            orders.setPayStatus(Orders.REFUND);
        }
        orders.setStatus(Orders.CANCELLED); //订单状态
        orders.setCancelReason("用户取消"); //取消原因
        orders.setCancelTime(LocalDateTime.now()); //取消时间
        orderMapper.update(orders); //修改
    }

    /**
     * 用户再来一单
     *
     * @param id 订单ID
     */
    @Override
    public void anotherOrder(Long id) {
        // 查询当前用户id
        Long userId = ThreadLocalUtil.get();

        // 根据订单id查询当前订单详情
        List<OrderDetail> orderDetailList = orderDetailMapper.findByOrderId(id);

        // 将订单详情对象转换为购物车对象
        List<ShoppingCart> shoppingCartList = orderDetailList.stream().map(x -> {
            ShoppingCart shoppingCart = new ShoppingCart();

            // 将原订单详情里面的菜品信息重新复制到购物车对象中
            BeanUtils.copyProperties(x, shoppingCart, "id");
            shoppingCart.setUserId(userId);
            shoppingCart.setCreateTime(LocalDateTime.now());

            return shoppingCart;
        }).collect(Collectors.toList());
        // 将购物车对象批量添加到数据库
        shoppingCartMapper.insertBatch(shoppingCartList);
    }

    /**
     * 接单
     *
     * @param confirmDTO dto
     */
    @Override
    public void confirm(OrdersConfirmDTO confirmDTO) {
        Orders orders = orderMapper.findById(confirmDTO.getId());
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        orderMapper.update(Orders.builder().id(confirmDTO.getId()).status(Orders.CONFIRMED).build());
    }

    /**
     * 订单搜索
     *
     * @param queryDTO dto
     * @return 分页数据
     */
    @Override
    public PageResult<OrderVO> conditionSearch(OrdersPageQueryDTO queryDTO) {
        PageHelper.startPage(queryDTO.getPage(), queryDTO.getPageSize());
        Page<Orders> ordersPage = orderMapper.pageQuery(queryDTO);
        return new PageResult<>(ordersPage.getTotal(), getOrderVOList(ordersPage));
    }

    /**
     * 拒单
     *
     * @param rejectionDTO dto
     */
    @Override
    public void rejection(OrdersRejectionDTO rejectionDTO) {
        Orders ordersDB = orderMapper.findById(rejectionDTO.getId());
        // 订单只有存在且状态为2（待接单）才可以拒单
        if (ordersDB == null || !ordersDB.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Integer payStatus = ordersDB.getPayStatus();
        if (payStatus.equals(Orders.PAID)) {
//            String refund = weChatPayUtil.refund(ordersDB.getNumber(), ordersDB.getNumber(), new BigDecimal("0.01"), new BigDecimal("0.01"));
            log.info("用户退款");
        }
        Orders orders = new Orders();
        orders.setId(ordersDB.getId()); //订单id
        orders.setStatus(Orders.CANCELLED); //订单状态取消
        orders.setRejectionReason(rejectionDTO.getRejectionReason()); //取消原因
        orders.setCancelTime(LocalDateTime.now()); //取消时间
        orderMapper.update(orders);
    }

    /**
     * 取消订单
     *
     * @param cancelDTO dto
     */
    @Override
    public void cancel(OrdersCancelDTO cancelDTO) throws Exception {
        Orders ordersDB = orderMapper.findById(cancelDTO.getId());
        Integer payStatus = ordersDB.getPayStatus();
        if (payStatus.equals(Orders.PAID)) {
            //用户已支付，需要退款
//            String refund = weChatPayUtil.refund(ordersDB.getNumber(), ordersDB.getNumber(), new BigDecimal("0.01"), new BigDecimal("0.01"));
            log.info("申请退款");
        }
        //修改订单状态
        orderMapper.update(Orders.builder().id(cancelDTO.getId()).cancelTime(LocalDateTime.now()).status(Orders.CANCELLED).cancelReason(cancelDTO.getCancelReason()).build());
    }

    /**
     * 派送订单
     *
     * @param id 订单ID
     */
    @Override
    public void delivery(Long id) {
        Orders ordersDB = orderMapper.findById(id);
        if (ordersDB == null || !ordersDB.getStatus().equals(Orders.CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        orderMapper.update(Orders.builder().id(id).status(Orders.DELIVERY_IN_PROGRESS).build());
    }

    /**
     * 完成订单
     *
     * @param id 订单ID
     */
    @Override
    public void complete(Long id) {
        Orders ordersDB = orderMapper.findById(id);
        //订单只有派送中才能完成订单
        if (ordersDB == null || !ordersDB.getStatus().equals(Orders.DELIVERY_IN_PROGRESS)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        // 更新订单状态,状态转为完成
        orderMapper.update(Orders.builder().id(ordersDB.getId()).status(Orders.COMPLETED).deliveryTime(LocalDateTime.now()).build());
    }

    /**
     * 各个状态的订单数量统计
     *
     * @return 各个状态的订单数量统计
     */
    @Override
    public OrderStatisticsVO statistics() {
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        orderStatisticsVO.setToBeConfirmed(orderMapper.countStatus(Orders.TO_BE_CONFIRMED)); //待接单数量
        orderStatisticsVO.setConfirmed(orderMapper.countStatus(Orders.CONFIRMED)); //待派送数量
        orderStatisticsVO.setDeliveryInProgress(orderMapper.countStatus(Orders.DELIVERY_IN_PROGRESS));//派送中数量
        return orderStatisticsVO;
    }

    /**
     * 用户催单
     *
     * @param id 订单ID
     */
    @Override
    public void reminder(Long id) {
        Orders orders = orderMapper.findById(id);
        //订单状态不属于待接单的状态 抛出业务异常
        if (orders == null || !orders.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        //通过websocket 向客户端浏览器推送信息 type orderID CONTENT
        Map<String, Object> map = new HashMap<>();
        map.put("type", 2);
        map.put("orderId", id);
        map.put("content", "订单号" + orders.getNumber());
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }

    private List<OrderVO> getOrderVOList(Page<Orders> page) {
        // 需要返回订单菜品信息，自定义OrderVO响应结果
        List<OrderVO> orderVOList = new ArrayList<>();

        List<Orders> ordersList = page.getResult();
        if (!CollectionUtils.isEmpty(ordersList)) {
            for (Orders orders : ordersList) {
                // 将共同字段复制到OrderVO
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders, orderVO);
                String orderDishes = getOrderDishesStr(orders);

                // 将订单菜品信息封装到orderVO中，并添加到orderVOList
                orderVO.setOrderDishes(orderDishes);
                orderVOList.add(orderVO);
            }
        }
        return orderVOList;
    }

    /**
     * 根据订单id获取菜品信息字符串
     *
     * @param orders s
     * @return s
     */
    private String getOrderDishesStr(Orders orders) {
        // 查询订单菜品详情信息（订单中的菜品和数量）
        List<OrderDetail> orderDetailList = orderDetailMapper.findByOrderId(orders.getId());

        // 将每一条订单菜品信息拼接为字符串（格式：宫保鸡丁*3；）
        List<String> orderDishList = orderDetailList.stream().map(x -> x.getName() + "*" + x.getNumber() + ";").collect(Collectors.toList());

        // 将该订单对应的所有菜品信息拼接在一起
        return String.join("", orderDishList);
    }


}
